import { ref } from 'vue'

/**
* 下载文件 - 通用方法
*/
export const useDownload = () => {
  const isLoading = ref(false)

    /**
    * 通过 Blob 下载文件
    */
  const downloadFromBlob = async (blob: Blob, fileName: string) => {
    try {
      isLoading.value = true

      // 创建对象 URL
      const url = URL.createObjectURL(blob)

      // 创建临时链接并触发下载
      const link = document.createElement('a')
      link.href = url
      link.download = fileName
      document.body.appendChild(link)
      link.click()

      // 清理
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      return true
    } catch (error) {
      console.error('下载失败:', error)
      return false
    } finally {
      isLoading.value = false
    }
  }

  /**
  * 下载远程文件
  */
  const downloadRemoteFile = async (fileUrl: string, fileName: string) => {
    try {
      isLoading.value = true

      const response = await fetch(fileUrl)
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const blob = await response.blob()
      return await downloadFromBlob(blob, fileName)
    } catch (error) {
      console.error('下载远程文件失败:', error)
      return false
    } finally {
      isLoading.value = false
    }
  }

  /**
  * 下载文本内容
  */
  const downloadText = async (content: string, fileName: string, mimeType = 'text/plain') => {
    const blob = new Blob([content], { type: mimeType })
    return await downloadFromBlob(blob, fileName)
  }

  /**
  * 下载 JSON 数据
  */
  const downloadJSON = async (data: any, fileName: string) => {
    const content = JSON.stringify(data, null, 2)
    return await downloadText(content, fileName, 'application/json')
  }

  return {
    isLoading,
    downloadFromBlob,
    downloadRemoteFile,
    downloadText,
    downloadJSON
  }
}
